home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!news
- From: watzka@stat.uni-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: changing strings via pointers
- Date: 22 Feb 1996 19:18:32 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4gifi8$pau@sparcserver.lrz-muenchen.de>
- References: <1996Feb22.125436.25503@leeds.ac.uk>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- csyamc@scs.leeds.ac.uk (A M Casey) writes:
-
- >I reading in strings from a file using fgets, which stores the "\n" in
- >the array of chars which I have declared using a pointer.
-
- >The thing is, I want to get rid of the "\n" and replace it with "\0", but
- >obviously I can only do this using the pointer. I'm using the following code:
-
- First, let me suggest a "simple" solution for your problem. As in
- most cases, the standard C library is your friend. Have a look at
- strlen() and/or strchr().
-
- >char *Contents < pointer to string
-
- >int count = 0;
-
-
- >while (*(Contents + count)!= NULL) /* the end of string is not reached */
-
- I'd rather write this as
-
- while (Contents[count] != '\0')
-
- >{if (*(Contents + count) == atoi("\n"))
-
- I'd rather write this as
-
- if (Contents[count] == '\n')
-
- and in this case, it is not just a stylistic issue. "atoi("\n")" is
- certainly not what you want in this situation. It simply does not do
- what you probably want. "atoi("13")" might work on a lot of systems,
- though.
-
- >/* change the \n to a \0 and set the next char along to null */
- >{
- >*(Contents + count) = atoi("\0");
-
- Again, I'd rewrite this as
-
- Contents[count] = '\0';
-
- Your version will work, but maybe for reasons different from what
- you seem to think.
-
- >*(Contents + count + 1) = NULL;
-
- The string _is_ terminated by a '\0', and there is no need to
- terminate it by _two_ '\0' s
-
- >}
- >else
- >/* read in the next char */
- >{
- >count++;
-
- >I think the problem maybe my way of using the pointer - I can print out each
- >char as I get to it, but it doesnt seem to change the array at all.
- >Should I be using atoi?, it doesnt seem to work without it.
-
- 1) You should not use atoi(), at least not the way you do.
-
- 2) The error messages you got before you inserted atoi() might
- have pointed you in the right direction.
-
- 3) 'a' is an int in C. It is called a character constant.
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
- | ua302aa@sunmail.lrz-muenchen.de
-